package search

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

// BingResult 与TypeScript定义一致的搜索结果结构体
type BingResult struct {
	Title       string `json:"title"`
	URL         string `json:"url"`
	Description string `json:"description"`
	Source      string `json:"source"`
	Engine      string `json:"engine"`
}

// SearchBing 必应搜索函数，参数为查询词和结果数量限制
func SearchBing(query string, limit int) ([]BingResult, error) {
	var allResults []BingResult
	pn := 0 // 分页偏移量

	for len(allResults) < limit {
		// 构建查询参数
		params := url.Values{}
		params.Add("q", query)
		params.Add("first", fmt.Sprintf("%d", 1+pn*10)) // 分页参数：first=1,11,21...

		// 创建请求
		reqURL := "https://www.bing.com/search?" + params.Encode()
		req, err := http.NewRequest("GET", reqURL, nil)
		if err != nil {
			return nil, fmt.Errorf("创建请求失败: %w", err)
		}

		// 设置请求头（与原TS代码一致）
		req.Header.Set("authority", "www.bing.com")
		req.Header.Set("ect", "3g")
		req.Header.Set("pragma", "no-cache")
		req.Header.Set("sec-ch-ua-arch", "\"x86\"")
		req.Header.Set("sec-ch-ua-bitness", "\"64\"")
		req.Header.Set("sec-ch-ua-full-version", "\"112.0.5615.50\"")
		req.Header.Set("sec-ch-ua-full-version-list", "\"Chromium\";v=\"112.0.5615.50\", \"Google Chrome\";v=\"112.0.5615.50\", \"Not:A-Brand\";v=\"99.0.0.0\"")
		req.Header.Set("sec-ch-ua-model", "\"\"")
		req.Header.Set("sec-ch-ua-platform-version", "\"15.0.0\"")
		req.Header.Set("sec-fetch-user", "?1")
		req.Header.Set("upgrade-insecure-requests", "1")
		req.Header.Set("Cookie", "MUID=3727DBB14FD763511D80CDBD4ED262EF; MSPTC=5UlNf4UsLqV53oFqqdHiR26FwDDL8zSW3kC74kIJQfM; _EDGE_S=SID=132F08F578E06F832D931EE779E16E2D; MUIDB=3727DBB14FD763511D80CDBD4ED262EF; SRCHD=AF=NOFORM; SRCHUID=V=2&GUID=B3AFD0E41DB649E39803C690946C3B65&dmnchg=1; ak_bmsc=578AE2B7DA55FA9F332ADCDFBA0B9B64~000000000000000000000000000000~YAAQZCg0F9XLkYGXAQAAjywwkhxcD6Pm2nguBmpB14hnmCR3kz9Mfau5cZ7pwHxdU2Uog9+6hOkBmzpOV3UoTOhi52nB725xM7zN90mRDv0zQtJdO/llaKlt2zqTmB4F5kd+GzPjXLAN4Zmj4KwpAjLK1T4TexH/9WlQTkRamdJTKuR47IZWHHebqsbNqHoYncHhxICO9Rnu51vhlps/rrhPBtgPgbrQnDfr6YzAQWmSqc5g9hk03sM9nnWUyVbRV0ZVsgke7BCYX5V1JD5L0Zf8/FWdntBpjpd2IcmehBz38ChGThPrBEWNCZQbCS6lE4OaQanrrdmBHf/r5YEf2LeIqZy0bJGIiSQaSh6d7KFO2haTQk/JscZAs+V5kNsAOxIGreRve+E=; _UR=QS=0&TQS=0&Pn=0; BFBUSR=BFBHP=0; SRCHUSR=DOB=20250621&DS=1; _Rwho=u=d&ts=2025-06-21; ipv6=hit=1750507922628&t=4; BFPRResults=FirstPageUrls=C5E678E900F98310F0D3DB1F3EB96D99%2CB5A20FAE72B0C3019A56409EAC7AF3FB%2C7A44A77FF42EDF11CC9BF5CFE08B179A%2C6ED615E5E634BD5AFC7BB2A0A77F8FF8%2CA993E7AAF4890BEC06882621CA376D00%2C49CF0FC3C203D5E918A76258506B0CF4%2C7F03D5026C1D046F66B11D525095BF8B%2C058BB67A6B7F15E58D3A19B897BC57F8%2C1B886024FDE703428D24A41AFA1E62AF%2C5A8B56DC0AE03A8B94643DEA2A22DBAC&FPIG=05F126AA95514CF5AD5E33E4AEBA474D; _HPVN=CS=eyJQbiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiUCJ9LCJTYyI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiSCJ9LCJReiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiVCJ9LCJBcCI6dHJ1ZSwiTXV0ZSI6dHJ1ZSwiTGFkIjoiMjAyNS0wNi0yMVQwMDowMDowMFoiLCJJb3RkIjowLCJHd2IiOjAsIlRucyI6MCwiRGZ0IjpudWxsLCJNdnMiOjAsIkZsdCI6MCwiSW1wIjoxNSwiVG9ibiI6MH0=; _C_ETH=1; _RwBf=r=0&ilt=15&ihpd=1&ispd=14&rc=36&rb=0&rg=200&pc=36&mtu=0&rbb=0&clo=0&v=15&l=2025-06-21T07:00:00.0000000Z&lft=0001-01-01T00:00:00.0000000&aof=0&ard=0001-01-01T00:00:00.0000000&rwdbt=0&rwflt=0&rwaul2=0&g=&o=2&p=&c=&t=0&s=0001-01-01T00:00:00.0000000+00:00&ts=2025-06-21T11:36:08.7064260+00:00&rwred=0&wls=&wlb=&wle=&ccp=&cpt=&lka=0&lkt=0&aad=0&TH=&cid=0&gb=; _SS=SID=132F08F578E06F832D931EE779E16E2D&R=36&RB=0&GB=0&RG=200&RP=36; SRCHHPGUSR=SRCHLANG=zh-Hans&IG=63A0A44F5D2F4499AD165A366D073C03&DM=0&BRW=N&BRH=T&CW=1202&CH=1289&SCW=1185&SCH=2279&DPR=1.0&UTC=480&HV=1750505768&HVE=notFound&WTS=63886101120&PV=15.0.0&PRVCW=1202&PRVCH=1289&EXLTT=13; SRCHHPGUSR=SRCHLANG=en&IG=9A53F826E9C9432497327CA995144E14&DM=0&BRW=N&BRH=T&CW=1202&CH=1289&SCW=1185&SCH=2279&DPR=1.0&UTC=480&HV=1750505768&HVE=notFound&WTS=63886101120&PV=15.0.0&PRVCW=1202&PRVCH=1289&EXLTT=13")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36")
		req.Header.Set("Accept", "*/*")
		req.Header.Set("Host", "cn.bing.com")
		req.Header.Set("Connection", "keep-alive")

		// 发送请求（15秒超时）
		client := &http.Client{Timeout: 15 * 60}
		resp, err := client.Do(req)
		if err != nil {
			return nil, fmt.Errorf("发送请求失败: %w", err)
		}
		defer resp.Body.Close()

		// 检查响应状态
		if resp.StatusCode != http.StatusOK {
			return nil, fmt.Errorf("请求失败，状态码: %d", resp.StatusCode)
		}

		// 解析HTML
		doc, err := goquery.NewDocumentFromReader(resp.Body)
		if err != nil {
			return nil, fmt.Errorf("解析HTML失败: %w", err)
		}

		var pageResults []BingResult

		// 提取搜索结果（与原TS选择器逻辑一致）
		doc.Find("#b_content").Children().Find("#b_results").Children().Each(func(i int, s *goquery.Selection) {
			titleElement := s.Find("h2")
			linkElement := s.Find("a")

			// 检查标题和链接是否存在
			if titleElement.Length() > 0 && linkElement.Length() > 0 {
				url, exists := linkElement.Attr("href")
				if !exists || !strings.HasPrefix(url, "http") {
					return // 跳过无效链接
				}

				// 提取描述和来源
				description := strings.TrimSpace(s.Find("p").First().Text())
				source := strings.TrimSpace(s.Find(".b_tpcn").Text())

				// 添加到结果集
				pageResults = append(pageResults, BingResult{
					Title:       strings.TrimSpace(titleElement.Text()),
					URL:         url,
					Description: description,
					Source:      source,
					Engine:      "bing",
				})
			}
		})

		// 合并结果
		allResults = append(allResults, pageResults...)

		// 无更多结果时提前结束
		if len(pageResults) == 0 {
			fmt.Println("⚠️ No more results, ending early....")
			break
		}

		// 准备下一页
		pn += 1
	}

	// 截取到指定数量的结果
	if len(allResults) > limit {
		allResults = allResults[:limit]
	}

	return allResults, nil
}
